import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  NotFoundException,
} from '@nestjs/common';
import { TasksService } from '../tasks.service';
import { TaskType, UserRole } from '../../common/enums';

@Injectable()
export class TaskEditGuard implements CanActivate {
  constructor(private readonly tasksService: TasksService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const taskId = request.params.taskId;

    // Admin users can edit any task
    if (user.role === UserRole.ADMIN) {
      return true;
    }

    // For non-admin users, check if the task is global
    try {
      const task = await this.tasksService.findOne(taskId);

      // If the task is global, regular users cannot edit it
      if (task.type === TaskType.GLOBAL) {
        throw new ForbiddenException('Regular users cannot edit global tasks');
      }

      // Check if the task is assigned to the current user
      if (task.assignedUserId !== user.userId) {
        throw new ForbiddenException('You can only edit tasks assigned to you');
      }

      return true;
    } catch (error) {
      // If the error is already a ForbiddenException, rethrow it
      if (error instanceof ForbiddenException) {
        throw error;
      }
      // If the task is not found, rethrow the NotFoundException to let the controller handle it
      if (error instanceof NotFoundException) {
        throw error;
      }
      // For other errors, return false
      return false;
    }
  }
}
